#!/bin/bash

# Push this service to a remote server and start it.
# If an older service is running, stop it first.

SCRIPTNAME="${0##*/}"
USERATHOST=$1

# Check arguments
if [ $# -ne 1 ]
then
  echo "Usage: $SCRIPTNAME user@host"
  exit 1
fi

# The local "service folder" is the one this script is in.
SERVICEFOLDER=$(cd "$0/.."; pwd)
echo $SERVICEFOLDER

# Make directories on the server if they don't already exist.
ssh "$USERATHOST" 'mkdir -pv ~/golimojo'
if [ $? -ne 0 ]
then
  echo "!!! mkdir failed -- aborting!"
  exit 1
fi

# Use rsync to update the staging folder on the remote server.
# Note trailing slash on the source (local) directory.
rsync --verbose --recursive --delete -e ssh "$SERVICEFOLDER/" "$USERATHOST:golimojo/staging"
if [ $? -ne 0 ]
then
  echo "!!! rsync failed -- aborting!"
  exit 1
fi

# Now that the files have been copied to the remote service, actually install it.
# Note that we don't check the exit code here since the install script doesn't exit
# until the user forcibly kills it, resulting in a non-zero status code. 
ssh "$USERATHOST" 'source ~/.bash_profile; ~/golimojo/staging/install-service.sh ~/golimojo/staging'

